package com.qgs.rabbitmqapi.confirm;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;

/**
 * @Author: 蔡翔
 * @Date: 2019/7/19 9:03
 * @Version 1.0
 */
public class Producer {
    public static void main(String[] args) throws Exception {
        //1.创建ConnectionFactory
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setPort(5672);
        connectionFactory.setHost("192.168.0.229");
        connectionFactory.setVirtualHost("/");

        //2.获取Connection
        Connection connection = connectionFactory.newConnection();

        //3.通过一个Connection创建一个新的channel
        Channel channel = connection.createChannel();

        //4.指定我们的消息投递模式：消息的确认模式
        channel.confirmSelect();
        String exchangeName = "test_confirms_exchange";
        String routringKey = "confirm.save";

        //5.发送一条消息
        String msg = "hello rabbitmq -send confirm message";
        channel.basicPublish(exchangeName,routringKey,null,msg.getBytes());

        //6.添加一个确认监听
        channel.addConfirmListener(new ConfirmListener() {
            @Override
            public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                //投递到broker失败的时候回进入到这个方法里面
                //deliveryTag是消息是否投递成功的依据。(这是一个标签。)
                System.out.println("------------ack-------------");
            }

            @Override
            public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                //投递到broker成功的时候回进入到这个方法里面
                System.out.println("------------no ack-------------");
            }
        });
    }
}
